package features;

import java.util.Collection;
import java.util.Collections;

import model.Category;
import model.Document;
import model.Term;

public class CHIReductor {
	Collection<Category> categories;
	Collection<Term> terms;
	Collection<Document> documents;

	public CHIReductor(Collection<Category> categories, Collection<Term> terms,
			Collection<Document> documents) {
		this.categories = categories;
		this.terms = terms;
		this.documents = documents;
	}

	public void calculateCHI() {

		for (Term term : terms) {
			double chiSum = 0.0;
			for (Category category : categories) {
				Collection<Document> categoryDocs = category.getCategoryDocs();
				int Di = term.getDocuments().size();
				int Dk = categoryDocs.size();
				int N = documents.size();

				int Tik = 0;
				int Fik = 0;
				
				
				for (Document categoryDoc : categoryDocs) {
					if (term.getDocuments().containsKey(Integer.toString(categoryDoc.getId()))){
						Tik++;
					} else {
						Fik++;
					}
				}

				double Pi = ((double) Di) / ((double) N);
				double Pk = ((double) Dk) / ((double) N);
				double Pik = Pi * Pk;
				double Pnik = (1.0 - Pi) * Pk;

				chiSum += Math.pow((((double) Tik) - Pik * N), 2) / (Pik * N)
						+ Math.pow((((double) Fik) - Pnik * N), 2) / (Pnik * N);
			}
			term.setChisq(chiSum);
		}
	}
}
